import numpy as np

def jointHistogram_(img, boundary, bin_size):

    interval = (boundary[1] - boundary[0] + 1) / bin_size
    
    if len(img.shape) > 2:
        hist_size = bin_size ** img.shape[2]
        img_bin = np.zeros([img.shape[0], img.shape[1]], np.int32)
        for i in range(img.shape[2]):
            img_bin += ((img[:, :, i] - boundary[0]) / interval) * (bin_size ** i)
    else:
        hist_size = bin_size
        img_bin = (img - boundary[0]) / interval

    unique, count = np.unique(img_bin, return_counts=True)


    histogram = np.zeros([hist_size])
    for u, c in zip(unique, count):
        histogram[u] = c

    return histogram

def jointHistogram(img,mask, boundary, bin_size):

    interval = (boundary[1] - boundary[0] + 1) / bin_size
    
    if len(img.shape) > 2:
        hist_size = bin_size ** img.shape[2]
        img_bin = np.zeros([img.shape[0], img.shape[1]], np.int32)
        for i in range(img.shape[2]):
            img_bin += ((img[:, :, i] - boundary[0]) / interval) * (bin_size ** i)
    else:
        hist_size = bin_size
        img_bin = (img - boundary[0]) / interval
    if not mask is None:
        img_bin = np.where(mask,img_bin,-1)         #@wei
    unique, count = np.unique(img_bin, return_counts=True)

    histogram = np.zeros([hist_size])   #+1
    for u, c in zip(unique, count):
        if u>=0:
            histogram[u] = c
    return histogram


import cv2
import matplotlib.image as mpimg
import matplotlib.pyplot as plt

def main():
    img = mpimg.imread('/Users/gerrie/trainingData/reid/Market-1501-v15.09.15/query/0005_c2s1_000976_00.jpg')
    mask = mpimg.imread('/Users/gerrie/trainingData/reid/Market-1501-v15.09.15/query_seg_0926/FCN8_adam_iter_35000/gray/0005_c2s1_000976_00.jpg')
    mask = np.where(mask==1,1,0)
    # cv2.resize(img,mask.shape[0],mask.shape[1])
    img = cv2.resize(img,(mask.shape[1],mask.shape[0]),interpolation=cv2.INTER_NEAREST)

    img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    hsv_hist = jointHistogram(
        img_hsv,
        mask,
        [0, 255],
        8
    )

    origin_hsv = jointHistogram_(img_hsv,[0,255],8)
    # n, bins, patches = plt.hist(hsv_hist, 512, normed=1, facecolor='green', alpha=0.75)
    plt.bar(np.arange(hsv_hist.shape[0]), hsv_hist, 0.35, color='r')
    plt.figure()
    plt.bar(np.arange(origin_hsv.shape[0]),origin_hsv,0.35,color='blue')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.axis([0, 512, 0, 50])
    plt.grid(True)

    plt.show()
    # plt.
def main2():
    img = cv2.imread('../../LOMO_XQDA/images/000_45_a.bmp')
    img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    hsv_hist = jointHistogram_(img_hsv,[0,255],8)
    print hsv_hist

if __name__ == '__main__':
    main2()
